package com.campus.customer.service;

import com.campus.common.message.OrderCancelMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 订单取消消息消费者
 * 监听Kafka中的订单取消消息，并发送微信订阅消息给顾客
 */
@Service
@Slf4j
public class OrderCancelMessageConsumer {
    @Resource
    private ObjectMapper objectMapper;
    @Autowired
    private WechatSubscribeMessageService wechatSubscribeMessageService;

    /**
     * 监听订单取消消息
     * @param message 订单取消消息
     */
    @KafkaListener(topics = "order-cancel", groupId = "customer-group")
    public void handleOrderCancelMessage(String message) {
        OrderCancelMessage orderCancelMessage = null;
        try {
            orderCancelMessage = objectMapper.readValue(message, OrderCancelMessage.class);
            log.info("接收到订单取消消息，订单号: {}, 用户openId: {}", 
                    orderCancelMessage.getOrderId(), orderCancelMessage.getOpenId());
            
            // 发送微信订阅消息
            wechatSubscribeMessageService.sendOrderCancelMessage(
                orderCancelMessage.getOpenId(),
                orderCancelMessage.getOrderId(),
                "¥" + orderCancelMessage.getOrderAmount().toString(),
                orderCancelMessage.getCancelReason()
            );
            
            log.info("订单取消消息处理完成，订单号: {}", orderCancelMessage.getOrderId());
            
        } catch (Exception e) {
            if(orderCancelMessage == null){
                log.error("处理订单取消消息失败，消息内容: {}", message, e);
            }else{
                log.error("处理订单取消消息失败，订单号: {}, 用户openId: {}",
                        orderCancelMessage.getOrderId(), orderCancelMessage.getOpenId(), e);
            }
            // Kafka会自动重试，无需手动处理
        }
    }
}